import React from 'react';
import HeaderNav from 'shared/components/HeaderNav';
import { Link } from 'react-router-dom';
import Checkbox from 'antd-mobile/lib/checkbox';
import Toast from 'antd-mobile/lib/toast';
import { delWish, addWish } from 'shared/commonFetch/index';
import Menu from 'shared/components/Menu';
import { fetchCareList,fetchCareCtrl,fetchCareDel } from './api/index';
import CartItem from './CartItem';
import CartEmpty from './CartEmpty';
import './index.less';

const warn = require('src/static/warn.png');

export default class Cart extends React.PureComponent {
  constructor(props){
    super(props)
    this.dot = 0;
    this.state = {
      resData:[],
      allChecked:false,
      totalPrice:0,
    }
  }

  countTotal = (data) =>{
    let totalPrice = 0;
    data.forEach((item)=>{
      if(item.selected === true){
        totalPrice += (item.quantity * item.price);
      }
    })
    this.setState({totalPrice})
  }


  listData= () => {
    fetchCareList(this.userInfo).then((res)=>{
      if(res.data.every((item)=>{return item.selected === true})){
        this.setState({allChecked:true})
      }else{
        this.setState({allChecked:false})
      }
      this.countTotal(res.data);
      this.setState({
        resData:res.data
      })
    })
  }
  careCtrl = (data) => {
    fetchCareCtrl(data).then((res)=>{
      if(res.code === 1000){
        this.listData();
      }
    })
  }
  componentDidMount(){
    this.listData();
  }


  //数量控制
  numChange = (Newval,val,id) => {
    let data = {};
    if(Newval == val + 1){
      data.operator = 'increase'
    }else if(Newval == val - 1){
      data.operator = 'decrease'
    }else{
      data.operator = 'quantity',
      data.quantity = Newval
    }
    data.product_id = id;
    this.careCtrl(data);
  }
  //关注控制
  wishCtrl = (status,id) => {
    if(status){
      delWish(id)
    }else{
      addWish(id)
    }
    this.listData();
  }
  //删除商品
  del = (id) => {
    const data = {};
    data.product_id = id
    fetchCareDel(data).then((res)=>{
      if(res.code === 1000){
        Toast.success('删除成功！', 1)
        this.listData();
      }
    })
  }
  careCheckedChange = (val,id) => {
    const data = {};
    if(val){
      data.operator = 'unselected';
    }else{
      data.operator= 'selected';
    }
    data.product_id = id;
    this.careCtrl(data);
  }
  allChange = (val) =>{
    const data = {};
    if(val){
      data.operator = 'unselectedall';
    }else{
      data.operator= 'selectedall';
    }
    this.careCtrl(data);
  }

  loginShowHandle() {
    __self.history.push('/Login')
  }

  redirectCheckoutCart = (isDisable) => {
    if (isDisable) {
      return;
    }
    const { resData } = this.state;
    let quantitySufficient = false;
    for (let i = 0; i < resData.length; i++){
      let item = resData[i];
      if (item.selected && (item.quantity > item.totalquantity)) {
        Toast.fail(`${item.title} 库存数量不足`)
        quantitySufficient = true;
        break;
      }
    }

    if (quantitySufficient) {
      return;
    }

    this.props.history.push('/OrderDetails/buyCart')
  }

  render() {
    const { resData, allChecked, totalPrice } = this.state;
    const userInfo = window.localStorage.getItem('userInfo');
    return (
      [
        <HeaderNav key="HeaderNav" showSearch={false} title="购物车" />,
        (
          <div className="cart" key="cart">
            <div className="cart-loginout-show">
              {
                !userInfo && (
                  <div>
                    <img src={warn} alt="" />
                    <span>您还没有登录！登录后购物车的商品将保存到您账号中</span>
                    <div className="btn" onClick={this.loginShowHandle}>立刻登录</div>
                  </div>
                )
              }
            </div>
            {
              resData[0] ?
                <div className="cart-main">
                  <div className="cart-main-head"><span>全部商品</span></div>
                  <div className="cart-main-list">
                    {
                      resData.map((item,i)=>(
                        <CartItem
                          key={i}
                          data={item}
                          numChange={this.numChange}
                          wishCtrl={this.wishCtrl}
                          careCheckedChange={this.careCheckedChange}
                          del={this.del}
                        />
                      ))
                    }
                  </div>
                </div>
                : <CartEmpty loginShowHandle={this.loginShowHandle} />
            }

            {
              resData[0] ?
                <div className="cart-ctrl">
                  <div>
                    <div className="cart-ctrl-checkbox">
                      <Checkbox checked={allChecked} onChange={()=>this.allChange(allChecked)} />
                      <span>全选</span>
                    </div>
                    <div className="cart-ctrl-btn">
                      <div className="msg">
                        <div className="msg-total">
                          <span>总计：</span>
                          <span>￥{totalPrice.toFixed(2)}</span>
                        </div>
                        <div className="msg-sale">
                          <span>总额￥{totalPrice.toFixed(2)}</span>
                          <span> 优惠￥0.00</span>
                        </div>
                      </div>
                      <div
                        className={totalPrice > 0 ? 'btn' : 'btn disableBtn'}
                        onClick={()=> { this.redirectCheckoutCart(totalPrice <= 0) }}
                      >
                        去结算
                      </div>
                    </div>
                  </div>
                </div> : <Menu />
            }
          </div>
        ),
      ])
  }
}